package com.cdwh.joylife.utils;

import android.graphics.Bitmap;
import android.os.Environment;

import com.cdwh.joylife.App;
import com.nanchen.compresshelper.CompressHelper;

import java.io.File;
import java.text.SimpleDateFormat;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by huxing on 2018/1/24.
 */

public class FileUtils {

    public static MultipartBody.Part convertPart(String image) {
        MultipartBody.Part part = null;
        File file = new File(image);
        if (file.exists()) {
            RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            part = MultipartBody.Part.createFormData("file", file.getName(), body);
        }
        return part;
    }

    public static MultipartBody.Part convertPart(File file) {
        MultipartBody.Part part = null;
        if (file.exists()) {
            RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            part = MultipartBody.Part.createFormData("file", file.getName(), body);
        }
        return part;
    }

    public static File getNewFile(File oldFile) {
        File file = new CompressHelper.Builder(App.getContext())
                .setMaxWidth(1080)  // 默认最大宽度为720
                .setMaxHeight(1920) // 默认最大高度为960
                .setQuality(100)    // 默认压缩质量为80
                .setFileName(getFileName()) // 设置你需要修改的文件名
                .setCompressFormat(Bitmap.CompressFormat.JPEG) // 设置默认压缩为jpg格式
                .setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
                        Environment.DIRECTORY_PICTURES).getAbsolutePath())
                .build()
                .compressToFile(oldFile);

        return file;
    }

    private static String getFileName() {

        String fileTime = TimeUtils.format(System.currentTimeMillis(), new SimpleDateFormat(TimeUtils.FILE_FORMAT));

        return new StringBuffer().append(fileTime).append("_").append("yqy_").append("c_share").toString();
    }
}
